package com.itheima.controller;


import com.itheima.dto.MessageConstant;
import com.itheima.dto.PageResult;
import com.itheima.dto.QueryPageBean;
import com.itheima.dto.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/member")
public class MemberController {
    /*
    注入会员的业务
     */
    @Autowired
    private MemberService memberService;

    /*/

     */
    @RequestMapping("/names")
    public Result getManagerNames() {
        List<Map<String, Object>> list = memberService.findManagerByRoleId();
        return Result.success(list, "查询健康管理师成功");
    }
    /*/
    分页查询
     */
    @PostMapping("/findPage")
    public PageResult findAll(@RequestBody QueryPageBean queryPageBean) {
        PageResult page = memberService.findPage(queryPageBean);
        return page;
    }
    /*/
    添加方法
     */
    @PostMapping
    public Result addMember(@RequestBody Member member) {
        memberService.add(member);
        return Result.success("添加成功");
    }
    /*/
    删除方法
     */
    @DeleteMapping("/{id}")
    public Result deleteMember(@PathVariable Integer id) {
        memberService.deleteById(id);
        return Result.success("删除成功");
    }
    /*
    /根据Id查询回显数据
     */
    @GetMapping("/{id}")
    public Result getMember(@PathVariable Integer id) {
        Member byId = memberService.findById(id);
        return Result.success(byId, "");
    }
    /*
    /编辑
     */
    @PutMapping
    public Result update(@RequestBody Member member) {
        memberService.edit(member);
        return Result.success("编辑成功");
    }


    @GetMapping("/exportExcel")
    public Result export(@RequestParam("ids") List<Integer> ids, HttpServletResponse response) {
        try {
            //List<String> names = memberService.ids

            List<Member> members = memberService.getMemberReportData(ids);
            //取出返回结果数据，准备将报表数据写入到Excel文件中

//            File file = ResourceUtils.getFile("classpath:static"
//                    + File.separator + "template" + File.separator + "member.xlsx");
            //String filePath = session.getServletContext().getRealPath("template") + File.separator + "member.xlsx";
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream("/usr/local/app/static/template/member.xlsx"));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            // sheet.setActiveCell();
            int countRow = 1;
            for (Member member : members) {
                XSSFRow row = sheet.createRow(countRow);
                String fileNumber = member.getFileNumber();//档案号
                String name = member.getName();//姓名
                String sex = member.getSex();//性别
                sex = ("1".equals(sex)) ? "男" : "女";
                DateUtils.dateDiff(member);
                String age = member.getAge().toString();
                Date regTime = member.getRegTime();
                String date = DateUtils.parseDate2String(regTime);
                String manager = member.getManager();
                String phoneNumber = member.getPhoneNumber();
                row.createCell(0).setCellValue(fileNumber.isEmpty() ? "" : fileNumber);
                row.createCell(1).setCellValue(name.isEmpty() ? "" : name);
                row.createCell(2).setCellValue(sex);
                row.createCell(3).setCellValue(age.isEmpty() ? "" : age);
                row.createCell(4).setCellValue(manager.isEmpty() ? "" : manager);
                row.createCell(5).setCellValue(date.isEmpty() ? "" : date);
                row.createCell(6).setCellValue(phoneNumber.isEmpty() ? "" : phoneNumber);
                Integer memberId = member.getId();
                List<String> names = memberService.findNames(memberId);
                String setMeal=names.isEmpty() ? "" : names.get(0);
                String substring = setMeal.substring(1, setMeal.length() - 1);
                row.createCell(7).setCellValue(substring);
                countRow++;
            }

            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型 content-type  application/vnd.ms-excel
            // response.setHeader("Content-Type","application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=member.xlsx");//指定以附件形式进行下载 强制下载！！
            excel.write(out);

            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            return Result.error(MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }

    }
}

